﻿using AutoMapper;
using B.S.DataBase.MyProject.Domain.基础设置;
using B.S.DataBase.MyProject.ErrorCode;
using B.S.DataBase.MyProject.Infrastructure;
using MediatR;
using MedicalPCTerminal.Read.API.Appcation.Commands.BasicSettings;
using MedicalPCTerminal.Read.API.Dtos;

namespace MedicalPCTerminal.Read.API.Appcation.CommandHandlers.BasicSettings
{
    /// <summary>
    /// 机构列表查询命令处理方法
    /// </summary>
    public class QueryOrganizationListCommandHandler : IRequestHandler<QueryOrganizationListCommand, APIResult<List<TeamInfoDto>>>
    {
        /// <summary>
        /// sqlsugar
        /// </summary>
        private readonly SqlSugarContext sugar;
        /// <summary>
        /// 映射
        /// </summary>
        private readonly IMapper mapper;

        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="sugar"></param>
        /// <param name="mapper"></param>
        public QueryOrganizationListCommandHandler(SqlSugarContext sugar, IMapper mapper)
        {
            this.sugar = sugar;
            this.mapper = mapper;
        }
        /// <summary>
        /// 处理方法
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<APIResult<List<TeamInfoDto>>> Handle(QueryOrganizationListCommand request, CancellationToken cancellationToken)
        {
            APIResult<List<TeamInfoDto>> result = new APIResult<List<TeamInfoDto>>();
            var model = sugar.db.Queryable<TeamInfo>();
            result.Code = APIEnum.查询成功;
            result.Msg = APIEnum.查询成功.ToString();
            result.data = GetTree(0);
            return await Task.FromResult(result);
        }

        public List<TeamInfoDto> GetTree(int id)
        {
            var teams = sugar.db.Queryable<TeamInfo>().Where(x => x.OrgNamePard == id).ToList();
            var dot = mapper.Map<List<TeamInfoDto>>(teams);
            foreach (var team in dot)
            {
                team.Children = GetTree(team.TeamID);
            }
            return dot;
        }


    }


}
